from piston.handler import BaseHandler
import datetime
from django.utils import simplejson

from models import Users
from models import SocialAccount
from models import Message

class CalcHandler( BaseHandler ):
		allow_method =('GET', 'POST','PUT', 'DELETE')
		
		#for GET method
		@classmethod
		def read( self, request, expression ):
				#CalcHandler.saveNewUser()
				try:
					emailaddr=request.GET.get('email_address')
					pwds=request.GET.get('password')
					objects = Users.objects.get(email_address=emailaddr, password=pwds)
					#objects = record.all()
					objects = CalcHandler.produceJSON(objects)
					#objects = [CalcHandler.produceJSON(o)   #for the result is a list of JSON
          #          for o in objects ]
					#if len(objects) == 1:
					#	objects = objects[0]
				except:
					return 'FAILED'
				else:
					return objects
		
		#for POST method
		@classmethod
		def create( self, request, expression):
				
				json_data = simplejson.loads(request.raw_post_data)
				
				new_user = Users(
				name = json_data['name'],
				email_address = json_data['email_address'],			
				password = json_data['password']
				)
				new_user.save()
				return 'SUCCESS'
		
		#for PUT method, define update method
		@classmethod
		def update( self, request, expression):

				json_data = simplejson.loads(request.raw_post_data)
				record = Users.objects.get(email_address=json_data['email_address'])
				
				record.password = json_data['password']
				record.save()

				return
				
		#for DELETE method, define delete method
		@classmethod
		def delete(self, request, expression):
				emailaddr=request.GET.get('email')
				record = Users.objects.get(email_address=emailaddr)
				
				record.delete()
				return
					
		@staticmethod
		def produceJSON(retobj):
			retval = {}
			retval['name'] = retobj['name']
			retval['email_address'] = retobj['email_address']
			return retval
			
		@staticmethod
		def saveNewUser():
			new_user=Users(
				name="lu",
				password="123",
				email_address="yang@cmu.edu",
				university="CMU", 
				credit_score=0.0, 
				friend_list=[0],
				group_list=[0],
				socialnetwork_account=[
				SocialAccount
				(
					network_type="linkedIn",
					username="lu",
					password="123"
				)
				],
				messagebox=[
				Message
				(
					sender_email="kai@cmu.edu",
					receiver_email="yang@cmu.edu",
					send_date=datetime.datetime.strptime("2012-04-12 15:30","%Y-%m-%d %H:%M"),
					content="hello!",
					carpool_no=0, 
					msg_type="regular", 
					msg_status="done"
				)
				]
			)
			new_user.save()
			return